import axios from "axios";
import dynamic from "next/dynamic";
import * as React from "react";
import getConfig from "next/config";

import "codemirror/lib/codemirror.css";
import "@toast-ui/editor/dist/toastui-editor.css";

const { publicRuntimeConfig } = getConfig();

const Editor = dynamic(() => import("./TuiEditorWrapper"), { ssr: false });
const ForwardedRefComponent = React.forwardRef((props, ref) => (
  <Editor {...props} forwardedRef={ref} />
));

const MDEditor = (props) => {
  const {
    initialValue,
    previewStyle,
    height,
    initialEditType,
    useCommandShortcut,
    token,
    id,
  } = props;

  const editorRef = React.useRef();

  const handleChange = React.useCallback(() => {
    if (!editorRef.current) {
      return;
    }

    const instance = editorRef.current.getInstance();
    const valueType = props.valueType || "markdown";

    props.onChange(
      valueType === "markdown" ? instance.getMarkdown() : instance.getHtml()
    );
  }, [props, editorRef]);

  function handleAddImageBlobHook(fileOrBlob, callback, source) {
    var forms = new FormData();
    // console.log("传递过来的token", props.token);
    var configs = {
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: "Bearer " + props.token,
      },
    };
    forms.append("file", fileOrBlob);
    axios
      .post(`${publicRuntimeConfig.baseURL}/image/upload`, forms, configs)
      .then((resp) => {
        // console.log("resp==>", resp);
        if (resp.status === 200 && resp.data.code === 1000) {
          callback(resp.data.data.uri, fileOrBlob.name);
        } else {
          alert(resp.data.message);
        }
      })
      .catch((err) => {
        console.log(err);
        alert("服务器错误");
      });
  }

  return (
    <ForwardedRefComponent
      {...props}
      initialValue={initialValue || "请输入正文内容"}
      previewStyle={previewStyle || "vertical"}
      height={height || "600px"}
      initialEditType={initialEditType || "markdown"}
      useCommandShortcut={useCommandShortcut || true}
      ref={editorRef}
      onChange={handleChange}
      hooks={{
        addImageBlobHook: handleAddImageBlobHook,
      }}
    />
  );
};

export default MDEditor;
